package com.ruoyi.ggsearch.service.impl;

import com.ruoyi.ggsearch.domain.GgDomain;
import com.ruoyi.ggsearch.domain.GgKeyWords;
import com.ruoyi.ggsearch.domain.GgSearchResult;
import com.ruoyi.ggsearch.mapper.GgSearchResultMapper;
import com.ruoyi.ggsearch.service.IGgSearchResultService;
import com.ruoyi.ggsearch.service.IGgSearchService;
import com.ruoyi.ggsearch.utils.ApiSearchTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.text.ParseException;
import java.util.*;

/**
 * 查询结果记录Service业务层处理
 * 
 * @author yangjin
 * @date 2023-04-07
 */
@Service
public class GgSearchServiceImpl implements IGgSearchService
{

    @Autowired
    private IGgSearchResultService ggSearchResultService;
    @Autowired
    private GgSearchResultMapper ggSearchResultMapper;

    @Override
    public void goSearchAndSave(List<GgKeyWords> listKeyWords, List<GgDomain> listDomain) throws Exception {
        if(listKeyWords!=null && listKeyWords.size()>0)
        {
            ggSearchResultMapper.deleteGgSearchResultAll();//查询前删除当天的搜索记录
            for(GgKeyWords keyWords: listKeyWords)
            {
                this.doSearch(keyWords.getKeyWord(), listDomain);
            }
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public void doSearch(String keyWord, List<GgDomain> listDomain) throws Exception {
        List<GgSearchResult> ggSearchResults = ApiSearchTool.doSearch(keyWord, listDomain);
        if(ggSearchResults!=null && ggSearchResults.size()>0)
        {
            System.out.println("关键字["+keyWord+"]查询完成，排名结果保存到数据库");
            for(GgSearchResult ggSearchResult : ggSearchResults)
            {
                /*List<GgSearchResult> list = ggSearchResultMapper.selectListByBean(ggSearchResult);//查找重复的记录
                if(list!=null && list.size()>0) {
                    for(GgSearchResult bean: list) {
                        System.out.println("发现重复:" + bean.getKeyId() + "---" + bean.getKeyWord() + "---" + bean.getDomain() + "---" + bean.getSearchDay());
                        ggSearchResultMapper.deleteGgSearchResultByKeyId(bean.getKeyId());
                    }
                }*/
                ggSearchResultService.insertGgSearchResult(ggSearchResult);
            }
        }
    }

}
